package com.alibaba.nacos.plugin.datasource.impl.kingbase8;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.plugin.datasource.constants.FieldConstant;
import com.alibaba.nacos.plugin.datasource.constants.TableConstant;
import com.alibaba.nacos.plugin.datasource.mapper.ConfigInfoBetaMapper;
import com.alibaba.nacos.plugin.datasource.model.MapperContext;
import com.alibaba.nacos.plugin.datasource.model.MapperResult;

import java.util.ArrayList;
import java.util.List;

import static com.alibaba.nacos.plugin.datasource.constants.DefaultConstant.DEFAULT_TENANT_ID;

public class ConfigInfoBetaMapperByKingbase8 extends AbstractKingbase8Mapper implements ConfigInfoBetaMapper {

    public MapperResult updateConfigInfo4BetaCas(MapperContext context) {
        String sql= "UPDATE config_info_beta SET content = ?,md5 = ?,beta_ips = ?,src_ip = ?,src_user = ?,gmt_modified = ?,app_name = ? "
                + "WHERE data_id = ? AND group_id = ? AND tenant_id = NVL(?,'" + DEFAULT_TENANT_ID + "') AND (md5 = ? or md5 is null or md5 = '')";


        List<Object> paramList = new ArrayList();
        paramList.add(context.getUpdateParameter(FieldConstant.CONTENT));
        paramList.add(context.getUpdateParameter(FieldConstant.MD5));
        paramList.add(context.getUpdateParameter(FieldConstant.BETA_IPS));
        paramList.add(context.getUpdateParameter(FieldConstant.SRC_IP));
        paramList.add(context.getUpdateParameter(FieldConstant.SRC_USER));
        paramList.add(context.getUpdateParameter(FieldConstant.APP_NAME));
        paramList.add(context.getWhereParameter(FieldConstant.DATA_ID));
        paramList.add(context.getWhereParameter(FieldConstant.GROUP_ID));
        paramList.add(context.getWhereParameter(FieldConstant.TENANT_ID));
        paramList.add(context.getWhereParameter(FieldConstant.MD5));

        return new MapperResult(sql, paramList);
    }

    @Override
    public MapperResult findAllConfigInfoBetaForDumpAllFetchRows(MapperContext context) {
        int startRow = context.getStartRow();
        int pageSize = context.getPageSize();

        String sqlInner = getDatabaseDialect().getLimitPageSqlWithOffset(
                "SELECT id FROM config_info_beta  ORDER BY id ", startRow, pageSize);
        String sql= " SELECT t.id,data_id,group_id,tenant_id,app_name,content,md5,gmt_modified,beta_ips,encrypted_data_key "
                + " FROM ( " + sqlInner + "  )"
                + "  g, config_info_beta t WHERE g.id = t.id ";
        return new MapperResult(sql,CollectionUtils.list(new Object[0]));
    }

    @Override
    public String getTableName() {
        return TableConstant.CONFIG_INFO_BETA;
    }
    @Override
    public String getFunction(String s) {
        return s;
    }


}
